<template>
  <div>
    <el-divider v-if="bindAccountList && bindAccountList.length" />
    <template
      v-for="ac in bindAccountList"
      :key="ac.id"
    >
      <el-row
        class="w100"
        align="middle"
        v-if="authTypes[ac.type]"
      >
        <el-col :span="3">
          {{ authTypes[ac.type] }}
        </el-col>
        <el-col :span="14">
          <div class="openid-wrap">
            <b class="mr10">OpenId:</b>
            {{ ac.openId }}
          </div>
        </el-col>
        <el-col :span="5">
          <div class="user-info-wrap">
            <span>{{ ac.userName }}</span>
            <el-avatar
              class="ml12"
              size="small"
              v-if="ac?.userInfo?.avatar"
              :src="ac?.userInfo?.avatar"
            />
          </div>
        </el-col>
        <el-col :span="2">
          <el-popconfirm
            :title="$t('system.bindAccount.confirmUnbind')"
            @confirm="handleUnBindAccount(getBindInfo(ac.type))"
          >
            <template #reference>
              <el-link
                type="danger"
                :underline="false"
              >
                {{ $t("system.bindAccount.unbind") }}
              </el-link>
            </template>
          </el-popconfirm>
        </el-col>
      </el-row>
    </template>
  </div>
</template>
<script setup lang="ts">
import { ref, watch } from "vue";
import { getBindAccountList, unBindAccount } from "@/api/system/userauth";
import { i18n } from "@/i18n";
import { MessageUtil } from "@/utils/messageUtil";

interface BindAccountInfo {
  type: number;
  userName: string;
  id: number;
  openId: string;
  userInfo: {
    avatar: string;
  };
}

// 授权类型定义
const authTypes: any = {
  1: i18n.global.t("system.bindAccount.wechatOpen"),
  2: i18n.global.t("system.bindAccount.wechatEnterprise"),
  5: i18n.global.t("system.bindAccount.wxMp")
};

const props = defineProps({
  userId: {
    type: Number,
    default: 0
  }
});

const bindAccountList = ref<BindAccountInfo[]>([]);

const getBindInfo = (type: number) => {
  return bindAccountList.value.find(item => item.type === type);
};

const handQueryBindAccountList = () => {
  getBindAccountList({
    userId: props.userId
  }).then(res => {
    bindAccountList.value = res.data;
  });
};

const handleUnBindAccount = (data: BindAccountInfo | undefined) => {
  unBindAccount(data).then(() => {
    MessageUtil.success(i18n.global.t("formI18n.all.success"));
    handQueryBindAccountList();
  });
};

const getBindAccount = (type: number) => {
  return bindAccountList.value.find(item => item.type === type);
};

watch(
  () => props.userId,
  () => {
    handQueryBindAccountList();
  },
  {
    immediate: true
  }
);
</script>

<style lang="scss" scoped>
.user-info-wrap {
  padding-left: 10px;
  display: flex;
  align-items: center;
}

.openid-wrap {
  display: flex;
  align-items: center;
}
</style>
